package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.domain.Brand;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.CategoryVo;
import com.spzx.product.vo.IndexDataVo;
import com.spzx.product.vo.ItemVo;
import com.spzx.product.vo.ProductSkuVo;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    BrandService brandService;

    @Autowired
    SkuStockService skuStockService;

    @Autowired
    ProductService productservice;

    @Autowired
    ProductDetailsService productDetailsService;


    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    //首页数据
    @Operation(summary = "首页数据")
    @GetMapping("/index")
    public AjaxResult indexData() {
        //1.创建首页VO对象
        IndexDataVo vo = new IndexDataVo();
        //2.封装一级分类列表
        List<CategoryVo> categoryVoList = categoryService.getLevelOneCategory();
        vo.setCategoryList(categoryVoList);

        //3.封装畅销TOP20商品列表
        List<ProductSkuVo> productSkuList = productSkuService.selectTopSale();
        vo.setProductSkuList(productSkuList);

        //4.响应VO
        return AjaxResult.success(vo);
    }



    //查询所有分类
    @Operation(summary = "查询所有分类")
    @GetMapping("/category")
    public AjaxResult categoryList() {
        List<CategoryVo> categoryVoList = categoryService.tree();
        return AjaxResult.success(categoryVoList);
    }

    @Operation(summary = "分页条件查询商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize
    , SkuQuery skuQuery){

        //开始分页
        PageHelper.startPage(pageNum,pageSize);
        //查询商品sku的列表
        List<ProductSkuVo> list=productSkuService.selectSkuList(skuQuery);
        return getDataTable(list);
    }

    @Operation(summary = "查询所有的品牌")
    @GetMapping("/brand")
    public AjaxResult listBrand(){
        List<Brand> list =brandService.list();
        return AjaxResult.success(list);
    }

/*
    @Operation(summary = "封装商品sku详情页数据")
    @GetMapping("/item/{skuId}")
    public AjaxResult item (@PathVariable("skuId") Long skuId){
        //创建itemvo对象
        ItemVo itemVo = new ItemVo();
        //为itemvo的七项属性赋值
        //根据skuid获取商品的sku信息
        ProductSku productSku = productSkuService.getproductSkuInfo(skuId);
        itemVo.setProductSku(productSku);
        //获取商品的最新价格信息(需要单独进行查询商品详情可能存在缓存或redis中,但价格不能存在缓存要是商品降价或者涨价不单独写一个接口,就会照成商品价格不败你)
        SkuPriceVo skuPrice= productSkuService.getSkuPrice(skuId);
        itemVo.setSkuPrice(skuPrice);
        //获取商品库存信息
        SkuStockVo skuStockVo= skuStockService.getSkuStock(skuId);
        itemVo.setSkuStock(skuStockVo);
        //获取轮播图信息
        Long productId = productSku.getProductId();
        Product byId = productservice.getById(productId);
        if(byId!=null && StringUtils.isNoneBlank(byId.getSliderUrls())){
            String sliderUrls = byId.getSliderUrls();
            itemVo.setSliderUrlList(sliderUrls.split(","));
        }
        //查询商品详情图片列表
        LambdaQueryWrapper<ProductDetails> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductDetails::getProductId,productId);
        ProductDetails productDetails = productDetailsService.getOne(lambdaQueryWrapper);
        if(productDetails!=null && StringUtils.isNoneBlank(productDetails.getImageUrls())){
            itemVo.setDetailsImageUrlList(productDetails.getImageUrls().split(","));
        }
        //查询商品规格信息
        String specValue = byId.getSpecValue();
        if(StringUtils.isNoneBlank(specValue)){
            JSONArray jsonArray = JSON.parseArray(specValue);
            itemVo.setSpecValueList(jsonArray);
        }
        //封装商品规格参数跟SKUID映射关系Map
        itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));

        //响应itemvo
        return AjaxResult.success(itemVo);

    }*/

    //线程池加异步编排优化商品详情
    @Operation(summary = "封装商品sku详情页数据")
    @GetMapping("/item/{skuId}")
    public AjaxResult item (@PathVariable("skuId") Long skuId) {
        //创建itemvo对象
        ItemVo itemVo = new ItemVo();

        //为ItemVo中七项属性逐一赋值
        //根据商品SKUID查询商品SKU信息  异步需要返回结果：商品SKU信息返回提供给 轮播图任务、详情图片任务、规格参数任务 使用
                                                            //CompletableFuture.supplyAsync不需要依赖任务但自己有返回值
        CompletableFuture<Long> productIdCompletableFuture = CompletableFuture.supplyAsync(() -> {
            ProductSku skuInfo = productSkuService.getproductSkuInfo(skuId);
            itemVo.setProductSku(skuInfo);
            //返回商品的id
            return skuInfo.getProductId();
        }, threadPoolExecutor);


        //查询商品SKU价格
        itemVo.setSkuPrice(productSkuService.getSkuPrice(skuId));
        //查询商品SKU库存
        itemVo.setSkuStock(skuStockService.getSkuStock(skuId));
        //查询商品轮播图列表  依赖商品ID异步任务，不需要有返回结果
                                                        // thenAcceptAsync依赖于其他任务自己不用有返回值
        CompletableFuture<Void> imageCompletableFuture = productIdCompletableFuture.thenAcceptAsync(productId -> {
            Product product = productservice.getById(productId);
            if (product != null && StringUtils.isNoneBlank(product.getSliderUrls())) {
                String sliderUrls = product.getSliderUrls();
                itemVo.setSliderUrlList(sliderUrls.split(","));
            }
            //查询商品详情图片列表
            ProductDetails productDetails = productDetailsService.getOne(
                    new LambdaQueryWrapper<ProductDetails>()
                            .eq(ProductDetails::getProductId, productId)
            );
            if (productDetails != null && StringUtils.isNoneBlank(productDetails.getImageUrls())) {
                itemVo.setDetailsImageUrlList(productDetails.getImageUrls().split(","));
            }
            //查询商品规格信息，展示规格信息用于用户选择
            String specValue = product.getSpecValue();
            if (StringUtils.isNoneBlank(specValue)) {
                JSONArray jsonArray = JSON.parseArray(specValue);
                itemVo.setSpecValueList(jsonArray);
            }
        }, threadPoolExecutor);


        //封装商品规格参数跟SKUID映射关系Map
        CompletableFuture<Void> skuSpecMapCompletableFuture = productIdCompletableFuture.thenAcceptAsync(productId -> {
            itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));
        }, threadPoolExecutor);

        //阻塞线程，等待所有任务完成
        CompletableFuture
                .allOf(
                        productIdCompletableFuture,
                        imageCompletableFuture,
                        skuSpecMapCompletableFuture)
                .join();//这是一个阻塞操作,会等待所有的线程都执行完后才会放行
        //响应ItemVo
        return success(itemVo);
    }



}